"""
@Project:workflow_python
@File:token_utils.py
@Author:袁浩天
@Date:19:31
"""

import jwt
import datetime
from django.conf import settings
import datetime
from jwt.exceptions import ExpiredSignatureError, DecodeError
from rest_framework.response import Response


# 生成token
def now_token(payload):
    token = jwt.encode(payload=payload, key=settings.SECRET_KEY, algorithm="HS256")
    return token


# 生成登录的token
def login_token(payload):
    """有效期为15天"""
    exp = datetime.datetime.now() + datetime.timedelta(days=15)
    payload["exp"] = exp
    token = now_token(payload)
    return token


# 验证token
def check_token(token):
    try:
        payload = jwt.decode(token, key=settings.SECRET_KEY, algorithms=["HS256"])
        return payload
    except ExpiredSignatureError:
        return Response({"code": 409, "msg": "token过期"})
    except DecodeError:
        return Response({"code": 408, "msg": "请重新登录"})


















